package {
	
	import flash.display.*;
	import flash.events.*;
	import flash.geom.Rectangle;
	import flash.net.*;
	
	public class KMC extends Sprite {
		public var ti:String = "";
		public var ar:String = "";
		public var al:String = "";
		public var by:String = "";
		public var offset:int = 0; // 延时  ms
		
		//配置==============================================
		
		//全局格式
		//提前多少毫秒准备一行
		public var preview_time:Number = 15000;
		//超过多少毫秒自动显示3秒倒计时（最开始除外）
		public var sec3_time:Number = 5000;
		//边距
		public var margin:int = 20;
		//行距
		public var leading:int = 10;
		//2行分别对齐
		public var align_one:String = "left";
		public var align_two:String = "right";
		//边框样式(包括发光滤镜)
		public var border:Object = {
			thickness : 2, 
			alpha : 0.8,
			blur : 2,
			strength: 10
		}
		public var border_color_base:uint = 0xffffff;
		public var border_color_upon:uint = 0xffdead;
		//字体样式
		public var format:Object = {
			font : "Arial", 
			size : 30,
			bold : true
		}
			// 基本颜色
		public var format_color_base:uint = 0x1e90ff;
		// 覆盖颜色
		public var format_color_upon:uint = 0xff6600;
		
		//==================================================
		
		public var karaoke:Array = [];
		public var main:Sprite = new Sprite();
		public var line_play:KmcLine;  //播放中的line
		
		public var backColor:uint = 0x0000ff;
		public var backAlpha:Number = 0.5;
		public var backWidth:Number = 760;
		public var backHeight:Number = 110;
		
		private var loader:URLLoader;
		public function KMC():void {
			addChild(main);
			drawBackground();
		}
		
		private function drawBackground():void
		{
			graphics.clear();
			graphics.beginFill(backColor, backAlpha);
			graphics.drawRect(0, 0, backWidth, backHeight);
			graphics.endFill();
		}
		
		public function init():void {
			clear();
		}
		
		public function clear():void {
			while(main.numChildren) {
				main.removeChildAt(0);
			}
		}
		
		public function load(url:String):void {
			init();
			loader = new URLLoader();
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError, false, 0, true);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError, false, 0, true);
			loader.addEventListener(ProgressEvent.PROGRESS, onProgress, false, 0, true);
			loader.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
			loader.load(new URLRequest(url));
		}
		
		public function stop():void {
			
		}
		
		public function update(t:Number):void {
			//配置是否已经准备
			if (!karaoke.length) {
				return;
			}
			line_play = null;
			for each(var l:KmcLine in karaoke) {
				l.update(t);
			}
			
		}
		
		//====================================================================
		private function onProgress(e:ProgressEvent):void {
			var per:String = "...";
			if (e.bytesTotal) {
				per = Math.round(e.bytesLoaded / e.bytesTotal * 100) + "%";
			}
		}
		private function onError(e:Event):void {
			init();
		}
		private function onComplete(e:Event):void {
			var str:String = String(e.target.data);
			if (str && str != " ") {
				parseKmc(str);
			} else {
				init();
			}
		}
		
		private function parseKmc(str:String):void {
			var xml:XML;
			try {
				xml = new XML(str);
			} catch (e:Error) {
				init();
				return;
			}
			//是否有子节点
			if (! xml.children().length()) {
				init();
				return;
			}
			//分析配置
			for each (var xas:XML in xml.attributes()) {
				var xn:String = xas.name().toString();
				if (this.hasOwnProperty(xn)) {
					if (this[xn] is int) {
						this[xn] = parseInt(xas.toString());
					} else if (this[xn] is String) {
						this[xn] = xas.toString();
					}
				}
			}
			//生成行列表
			karaoke = [];
			for each(var l:XML in xml.children()) {
				var line:KmcLine = new KmcLine(l, karaoke.length, this);
				karaoke.push(line);
				main.addChild(line);
			}
			if (!karaoke.length) {
				return;
			}
			//自动添加头信息数据，第一句空闲时间必须大于设置的预加载时间
			var t:Object = karaoke[0].time;
			if (t.start > preview_time + 1000) {
				var lgs:Array = ["歌名：", "原唱：", "专辑：", "制作："];
				var arr:Array = [ti, ar, al, by];
				var ais:Array = [];
				for (var j:int = 0; j < arr.length; j ++) {
					if (arr[j]) {
						ais.push(lgs[j] + arr[j]);
					}
				}
				var len:int = ais.length;
				if (len) {
					var ptime:Number = ((t.start - preview_time - 1000) / len) * 0.001;
					var ntime:Number = 0;
					var etime:Number = ptime;
					for (var i:int = 0; i < len; i ++) {
						var info:XML = new XML('<l t="' + ntime + ',' + etime + '">' + ais[i] + '</l>');
				trace(info);
						var iline:KmcLine = new KmcLine(info, karaoke.length, this);
						karaoke.push(iline);
						main.addChild(iline);
						ntime += ptime;
						etime += ptime;
					}
				}
			}
		}
		
		//=====================================================================
		
		public static const COLON:RegExp = /\s*\:\s*/;
		public static const COMMA:RegExp = /\s*\,\s*/;
		
		public static function output(o:Object):void {
			for (var k:String in o) {
				trace(k + " : " + o[k]);
			}
		}
		
		public static function parseTime(str:String, offset:Number):Object {
			var t:Object = {};
			if (str) {
				var arr:Array = array(str);
				t.start = parseMin(arr.shift()) + offset; // start表示开始时间
				t.end = parseMin(arr.shift()) + offset;   // 结束时间
				t.list = arr.map(parseNum);// 得到间隔时间
			}
			return t;
		}
		public static function parseNum(element: * ,index:int,arr:Array):Number {
			var v:Number = parseInt(element);
			if (isNaN(v)) {
				v = 0;
			}
			return v;
		}
		
		public static function parseMin(str:String):Number {
			var arr:Array = str.split(COLON);
			var max:int = arr.length;
			var kms:Number = 0;
			while (arr.length) {
				var v:Number = parseFloat(arr.pop());
				if (! isNaN(v)) {
					kms +=  v * Math.pow(60,max - arr.length - 1);
				}
			}
			kms = int(kms * 1000);
			return kms;
		}
		
		//切割并返回数组
		public static function array(input:String):Array {
			input = String(input);
			var arr:Array = input.split(COMMA);
			var out:Array = [];
			for each (var str:String in arr) {
				if (str) {
					out.push(str);
				}
			}
			return out;
		}
		
		public static function trim(input:String):String {
			return ltrim(rtrim(input));
		}
		
		// 去掉前面的空格
		public static function ltrim(input:String):String {
			var size:int = input.length;
			for(var i:int = 0; i < size; i++) {
				if(input.charCodeAt(i) > 32) {
					return input.substring(i);
				}
			}
			return "";
		}
		
		// 去掉后面的空格
		public static function rtrim(input:String):String {
			var size:int = input.length;
			for(var i:int = size; i > 0; i--) {
				if(input.charCodeAt(i - 1) > 32) {
					return input.substring(0, i);
				}
			}
			return "";
		}
	}
	
}
